package com.zz.inventory.controller;

import java.util.Date;
import java.util.List;
import java.io.IOException;

import com.zz.inventory.service.ILabsService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.zz.inventory.domain.Clients;
import com.zz.inventory.service.IClientsService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 客户端管理Controller
 * 
 * @author ruoyi
 * @date 2025-07-02
 */
@RestController
@RequestMapping("/clients")
public class ClientsController extends BaseController
{
    @Autowired
    private IClientsService clientsService;
    @Autowired
    private ILabsService labsService;

    /**
     * 查询客户端管理列表
     */
    @RequiresPermissions("schoolmanage:clients:list")
    @GetMapping("/list")
    public TableDataInfo list(Clients clients)
    {
        startPage();
        List<Clients> list = clientsService.selectClientsList(clients);
        return getDataTable(list);
    }

    /**
     * 导出客户端管理列表
     */
    @RequiresPermissions("schoolmanage:clients:export")
    @Log(title = "客户端管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Clients clients)
    {
        List<Clients> list = clientsService.selectClientsList(clients);
        ExcelUtil<Clients> util = new ExcelUtil<Clients>(Clients.class);
        util.exportExcel(response, list, "客户端管理数据");
    }

    /**
     * 获取客户端管理详细信息
     */
    @RequiresPermissions("schoolmanage:clients:query")
    @GetMapping(value = "/{clientId}")
    public AjaxResult getInfo(@PathVariable("clientId") Long clientId)
    {
        return success(clientsService.selectClientsByClientId(clientId));
    }

    /**
     * 新增客户端管理
     */
    @PostMapping
    @RequiresPermissions("schoolmanage:clients:add")
    @Log(title = "客户端管理", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody @Validated Clients clients) {
        // 1. IP地址格式校验（正则）
        if (!isValidIp(clients.getIpAddress())) {
            return AjaxResult.error("IP地址格式无效");
        }

        // 2. 调用Service插入
        int result = clientsService.insertClients(clients);
        return toAjax(result);
    }

    // 工具方法：IP地址正则校验
    private boolean isValidIp(String ip) {
        String ipRegex = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
        return ip != null && ip.matches(ipRegex);
    }

    /**
     * 修改客户端管理
     */
    @RequiresPermissions("schoolmanage:clients:edit")
    @Log(title = "客户端管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Clients clients)
    {
        // 更新客户端
        int result = clientsService.updateClients(clients);

        // 如果状态发生变化，同步更新机房状态
        if (result > 0) {
            labsService.updateLabStatusByClient(clients.getClientId(), clients.getStatus());
        }

        return toAjax(result);
    }

    /**
     * 删除客户端管理
     */
    @RequiresPermissions("schoolmanage:clients:remove")
    @Log(title = "客户端管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{clientIds}")
    public AjaxResult remove(@PathVariable Long[] clientIds)
    {
        return toAjax(clientsService.deleteClientsByClientIds(clientIds));
    }

    /**
     * 客户端心跳上报：更新心跳时间 + 强制在线
     */
    @PostMapping("/{clientId}/heartbeat")
    public AjaxResult heartbeat(@PathVariable("clientId") Long clientId) {
        // 1. 查询客户端（确保存在）
        Clients client = clientsService.selectClientsByClientId(clientId);
        if (client == null) {
            return AjaxResult.error("客户端不存在，请重新注册");
        }

        // 2. 更新心跳时间 + 强制设置在线状态
        client.setLastHeartbeat(new Date()); // 对应数据库字段：last_heartbeat
        client.setStatus("online");          // 核心：心跳上报即视为“在线”

        // 增加机房状态同步
        if ("online".equals(client.getStatus())) {
            labsService.updateLabStatusByClient(clientId, "online");
        }
        return AjaxResult.success("心跳上报成功", client);
    }
}
